﻿// Genius
// Copyright (C) 2016 Dirk Friedenberger, www.frittenburger.de
//   
// This source file is subject to the Microsoft Public License (Ms-PL).
// http://www.opensource.org/licenses/ms-pl.html
// All other rights reserved.
using Genius.Brain.Shared.Strategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Genius.Brain.Shared.BO;
using Newtonsoft.Json.Linq;
using System.IO;
using Genius.Brain.Shared;
using Genius.Brain.Shared.Locator;

namespace Genius.Brain.Impl.Strategy
{
    class TextFormaterStrategy : ITextFormaterStrategy
    {
        private IJsonDatabase<ITokenDatabaseRecord> _database;
        public TextFormaterStrategy(string[] fileNames)
        {
            _database = BrainLocator.GetTokenDatabase();
            foreach (var fileName in fileNames)
                _database.LoadFile(fileName);
        }
        public string Format(IText text)
        {
            foreach (var rec in _database.Data)
            {
                if (text.Token.Equals(rec.Token) && text.Language.Equals(rec.Language))
                {
                    String message = rec.Pattern[0];

                    for(int i = 0;i < 100;i++) //Endlosschleife verhindern
                    {
                        int s = message.IndexOf('{');
                        if (s < 0) break;
                        int e = message.IndexOf('}', s);
                        if (e < s) break;

                        String key = message.Substring(s + 1, e - s - 1);

                        if (!text.Params.ContainsKey(key)) break; //Error

                        string Value = text.Params[key];
                        message = message.Substring(0, s) + Value + message.Substring(e + 1);
                        
                    }
                    return message;
                }
            }

            return text.Token; //Fehler
        }
    }
}
